package com.rpcLearning.client;

import com.rpcLearning.common.ReflectUtils;
import com.rpclearnging.codec.Decoder;
import com.rpclearnging.codec.Encoder;

import java.lang.reflect.Proxy;

/**
 * @author:zyh
 * @Time:2021-03-17-21:21
 * @email:1269231889@qq.com
 */
public class RpcClient {
    private RpcClientConfig config;
    private Encoder encoder;
    private Decoder decoder;
    private TransportSelector selector;


    public RpcClient(RpcClientConfig config) {
        this.config = config;

        this.encoder = ReflectUtils.newInstance(
                this.config.getEncoder());
        this.decoder = ReflectUtils.newInstance(
                this.config.getDecoder());
        this.selector = ReflectUtils.newInstance(
                this.config.getSelector());

        this.selector.init(this.config.getServers(),
                            this.config.getConnectCount(),
                            this.config.getTransport()
                    );
    }

    public <T> T getProxy(Class<T> clazz){
        return (T) Proxy.newProxyInstance(
                getClass().getClassLoader(),
                new Class[]{clazz},
                new RemoteInvoker(clazz,encoder,decoder,selector)
        );
    }
}
